package com.xcx.robot.mirai.factory.facade;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.xcx.robot.mirai.config.UserConfig;
import com.xcx.robot.mirai.factory.BaseFacade;
import com.xcx.robot.mirai.key.KeyWord;
import com.xcx.robot.mirai.util.SenderHelper;
import com.xcx.robot.util.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.utils.ExternalResource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @Author: 邢晨旭
 * @Date: 2021/5/26 16:18
 * @Description:
 */
@Service
@Slf4j
public class ImageFacade implements BaseFacade {
    public KeyWord keyWord = KeyWord.IMAGE;
    @Resource
    UserConfig userConfig;

    @Override
    public void execute(Contact sender, Contact receiver, String content) {
        if((CollectionUtil.isEmpty(userConfig.getImageGroups())||CollectionUtil.isEmpty(userConfig.getImageUrls()))){
            return;
        }
        int count = userConfig.getImageUrls().size();
        if(userConfig.getImageGroups().contains(receiver.getId())||userConfig.getGmGroups().contains(receiver.getId())){
//            InputStream stream = HttpUtil.createGet(userConfig.getImageUrls().get(new Random().nextInt(count)),true).charset(StandardCharsets.UTF_8).execute().charset(StandardCharsets.UTF_8).bodyStream();
            String stream = "";
            int i = 0;
            while (true){
                stream = HttpUtil.createGet(userConfig.getImageUrls().get(new Random().nextInt(count))).charset(StandardCharsets.UTF_8).execute().charset(StandardCharsets.UTF_8).header("location");
                if(StringUtils.isNotEmpty(stream)){
                    log.info("涩图：{}",stream);
                    break;
                }
                i++;
                if(i>10){
                    receiver.sendMessage(new At(251238841L).plus("好像崩了"));
                }
            }
            ExternalResource externalResource = ImageUtils.initImage(stream);
            Image image = ExternalResource.uploadAsImage(externalResource, receiver);
            SenderHelper.sendMessage(receiver,image);
        }
    }


    @Override
    public KeyWord keyWord() {
        return keyWord;
    }
}
